<template>
    <div class="notice-page">
        <el-badge :value="number" class="item" :hidden="number === 0">
            <audio id="messageTip" controls="controls" hidden src="../../assets/image/msg.mp3"></audio>
            <el-dropdown trigger="click">
                <span class="el-dropdown-link">
                    <i class="el-icon-bell"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="noticeList">
                    <el-dropdown-item class="wdnumber">{{noticeNumber}}条未读消息</el-dropdown-item>
                    <el-dropdown-item v-for="item in noticeData">
                        <div class="p1">消息</div>
                        <div class="p2">有新的案件需要处理</div>
                        <el-button type="primary" size="mini" style="float: right;" @click="toNoticeDetails(item.eventId)">案件详情</el-button>
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </el-badge>
    </div>
</template>

<script>
    import Cookies from 'js-cookie'
    export default {
        name: 'index',
        data(){
            return{
                number: 0,
                noticeNumber: 0,
                ipUrl: 'ws://www.qjjxh.com:8081/handle-api',
                // ipUrl: 'ws://192.168.100.233:8080',
                // 登录的用户信息
                createUser: JSON.parse(localStorage.getItem('userInfo')),
                // 消息数据
                noticeData:[],

                ws: null,//建立的连接
                lockReconnect: false,//是否真正建立连接
                timeout: 28*1000,//30秒一次心跳
                timeoutObj: null,//心跳心跳倒计时
                serverTimeoutObj: null,//心跳倒计时
                timeoutnum: null,//断开 重连倒计时
            }
        },
        computed:{
            visitedViews() {
                return this.$store.state.tagsView.visitedViews
            },
        },
        methods:{
            initWebSocket1(){
                this.webSocket1 = new WebSocket(this.ipUrl + "/webSocket/" + this.createUser.userId);
                this.webSocket1.onopen = () => {
                    this.webSocket1.send('建立连接');//发送数据到服务端
                };
                this.webSocket1.onmessage = (e) =>  {
                    if (JSON.parse(e.data).eventId && JSON.parse(e.data).eventId != '0') {
                        this.noticeData.unshift(JSON.parse(e.data));
                        if(this.noticeData.length > 0){
                            this.number = this.noticeData && this.noticeData.length;
                            this.noticeNumber = this.noticeData && this.noticeData.length;
                            setTimeout(() => {
                                document.getElementById('messageTip').play();
                            }, 500)
                        }else{
                            this.number = 0;
                            this.noticeNumber = 0;
                        }
                    }
                };
                // 通信数据接收（来自详情页面查看案件的id）
                this.$lsbridge.subscribe('eventId', (data) => {
                    this.noticeData.forEach((item,index) => {
                        if (item.eventId == data.eventId) {
                            this.noticeData.splice(index, 1)
                        }
                    });
                    this.number = this.noticeData && this.noticeData.length;
                    this.noticeNumber = this.noticeData && this.noticeData.length;
                });
            },
            //跳转到详情页面
            toNoticeDetails(eventId){
                if(this.number > 0){
                    this.number -= 1;
                    this.noticeNumber -= 1;
                    let data = this.noticeData;
                    for(let i=0;i<data.length;i++){
                        if(data[i].eventId == eventId){
                            let index = data.indexOf(data[i]);
                            data.splice(index, 1);
                        }
                    }
                }
                this.$router.replace({
                    path: "/noticeDetails/index",
                    name: 'noticeDetails',
                    query: {
                        eventId:eventId
                    }
                });
                if (this.$route.name === "noticeDetails") {
                    //刷新详情标签
                    let viewsTabs=this.visitedViews;
                    for(let i=0;i<viewsTabs.length;i++){
                        if(viewsTabs[i].path == '/noticeDetails/index/'){
                            this.refreshSelectedTag(viewsTabs[i]);
                        }
                    }
                }
                if(this.number == 0){
                    this.noticeNumber = 0;
                }
            },
            //关闭当前标签
            closeSelectedTag(view) {
                this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
                    if (this.isActive(view)) {
                        this.toLastView(visitedViews, view)
                    }
                })
            },
            refreshSelectedTag(view) {
                this.$store.dispatch('tagsView/delCachedView', view).then(() => {
                    const { fullPath } = view;
                    this.$nextTick(() => {
                        this.$router.replace({
                            path: '/redirect' + fullPath
                        })
                    })
                })
            },
            isActive(route) {
                return route.path === this.$route.path
            },
            toLastView(visitedViews, view) {
                const latestView = visitedViews.slice(-1)[0];
                if (latestView) {
                    this.$router.push(latestView.fullPath)
                } else {
                    if (view.name === 'Dashboard') {
                        this.$router.replace({ path: '/redirect' + view.fullPath })
                    } else {
                        this.$router.push('/')
                    }
                }
            },

            initWebpack(){
                this.ws = new WebSocket(this.ipUrl + "/webSocket/" + this.createUser.userId);
                this.ws.onopen = this.onopen;
                this.ws.onmessage = this.onmessage;
                this.ws.onclose = this.onclose;
                this.ws.onerror = this.onerror;
            },
            reconnect() {//重新连接
                let that = this;
                if(that.lockReconnect) {
                    return;
                }
                that.lockReconnect = true;
                //没连接上会一直重连，设置延迟避免请求过多
                that.timeoutnum && clearTimeout(that.timeoutnum);
                that.timeoutnum = setTimeout( () => {
                    //新连接
                    that.initWebpack();
                    that.lockReconnect = false;
                },5000);
            },
            reset(){//重置心跳
                let that = this;
                //清除时间
                clearTimeout(that.timeoutObj);
                clearTimeout(that.serverTimeoutObj);
                //重启心跳
                that.start();
            },
            start(){//开启心跳
                var self = this;
                self.timeoutObj && clearTimeout(self.timeoutObj);
                self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
                self.timeoutObj = setTimeout(() => {
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    if (self.ws.readyState == 1) {//如果连接正常
                        self.ws.send("heartCheck");
                    }else{//否则重连
                        self.reconnect();
                    }
                    self.serverTimeoutObj = setTimeout(function() {
                        //超时关闭
                        self.ws.close();
                    }, self.timeout);

                }, self.timeout)
            },
            onopen() {
                // let msg = JSON.stringify({cmd: 'enter_chatting', token:Cookies.get('Admin-Token')});
                this.ws.send(1);
                //开启心跳
                this.start();
            },
            onmessage(e) {
                if (JSON.parse(e.data).eventId && JSON.parse(e.data).eventId != '0') {
                    this.noticeData.unshift(JSON.parse(e.data));
                    if(this.noticeData.length > 0){
                        this.number = this.noticeData && this.noticeData.length;
                        this.noticeNumber = this.noticeData && this.noticeData.length;
                        setTimeout(() => {
                            document.getElementById('messageTip').play();
                        }, 500)
                    }else{
                        this.number = 0;
                        this.noticeNumber = 0;
                    }
                }
                // 收到服务器信息，心跳重置
                this.reset();
            },
            onclose(e) {
                console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
                let msg = JSON.stringify({cmd: 'out_chatting', token:Cookies.get('Admin-Token')});
                this.ws.send(msg);
                //重连
                this.reconnect();
            },
            onerror(e) {
                //重连
                this.reconnect();
            }
        },

        created(){
            // this.initWebSocket1();
            this.initWebpack();

        },
        mounted(){
            // 通信数据接收（来自详情页面查看案件的id）
            this.$lsbridge.subscribe('eventId', (data) => {
                this.noticeData.forEach((item,index) => {
                    if (item.eventId == data.eventId) {
                        this.noticeData.splice(index, 1)
                    }
                });
                this.number = this.noticeData && this.noticeData.length;
                this.noticeNumber = this.noticeData && this.noticeData.length;
            });
        },
    }
</script>

<style lang="scss" scoped>
    .notice-page {
        display: inline-block;
        cursor: pointer;
        fill: #5a5e66;;
        width: 0.5rem;
        height: 0.25rem;
        vertical-align: 0.125rem;
    }
    .el-popper[x-placement^=bottom]{
        width:3.75rem;
        max-height: 2.975rem;
        overflow-y: auto;
        .el-dropdown-menu__item{
            height: 1.2rem;
        }
        .el-dropdown-menu__item.wdnumber{
            border-bottom:0.0125rem solid #ccc;
            height:auto;
            .p2{
                color:#bcbcbc;
            }
        }
    }
</style>
<style>
    .el-badge__content.is-fixed{
        right: 0.1rem;
        top: 0.1rem;
        padding: 0 0.05rem;
    }
    .el-icon-bell{
        font-size: 0.2625rem;
        font-weight: bold;
    }
</style>
